#
import argparse
import random
import time
from typing import Dict
import matplotlib.pyplot as plt
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F

class BlockDiagonal(nn.Module):
    def __init__(self, in_features, out_features, num_blocks, bias=True):
        super(BlockDiagonal, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.num_blocks = num_blocks
        assert out_features % num_blocks == 0
        block_out_features = out_features // num_blocks
        print(f'block_out_features: {block_out_features}; in_features: {in_features};')
        self.blocks = nn.ModuleList([
            nn.Linear(in_features, block_out_features, bias=bias)
            for _ in range(num_blocks)
        ])
        
    def forward(self, x):
        x = [block(x) for block in self.blocks]
        x = torch.cat(x, dim=-1)
        return x
    
class CausalConv1D(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, dilation=1, **kwargs):
        super(CausalConv1D, self).__init__()
        self.padding = (kernel_size - 1) * dilation
        self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, padding=self.padding, dilation=dilation, **kwargs)

    def forward(self, x):
        x = self.conv(x)
        return x[:, :, :-self.padding]

class MLstmBlock(nn.Module):
    def __init__(self, x_example, factor, depth, dropout=0.2):
        super().__init__()
        self.input_size = x_example.shape[2]
        self.hidden_size = int(self.input_size*factor)
        
        self.ln = nn.LayerNorm(self.input_size)
        
        self.left = nn.Linear(self.input_size, self.hidden_size)
        self.right = nn.Linear(self.input_size, self.hidden_size)
        
        self.conv = CausalConv1D(self.hidden_size, self.hidden_size, int(self.input_size/10)) 
        self.drop = nn.Dropout(dropout+0.1)
        
        self.lskip = nn.Linear(self.hidden_size, self.hidden_size)
        
        self.wq = BlockDiagonal(self.hidden_size, self.hidden_size, depth)
        self.wk = BlockDiagonal(self.hidden_size, self.hidden_size, depth)
        self.wv = BlockDiagonal(self.hidden_size, self.hidden_size, depth)
        self.dropq = nn.Dropout(dropout/2)
        self.dropk = nn.Dropout(dropout/2)
        self.dropv = nn.Dropout(dropout/2)
        
        self.i_gate = nn.Linear(self.hidden_size, self.hidden_size)
        self.f_gate = nn.Linear(self.hidden_size, self.hidden_size)
        self.o_gate = nn.Linear(self.hidden_size, self.hidden_size)

        self.ln_c = nn.LayerNorm(self.hidden_size)
        self.ln_n = nn.LayerNorm(self.hidden_size)
        
        self.lnf = nn.LayerNorm(self.hidden_size)
        self.lno = nn.LayerNorm(self.hidden_size)
        self.lni = nn.LayerNorm(self.hidden_size)
        
        self.GN = nn.LayerNorm(self.hidden_size)
        self.ln_out = nn.LayerNorm(self.hidden_size)

        self.drop2 = nn.Dropout(dropout)
        
        self.proj = nn.Linear(self.hidden_size, self.input_size)
        self.ln_proj = nn.LayerNorm(self.input_size)
        
        self.init_states(x_example)
    
    def init_states(self, x_example):
        self.ct_1 = torch.zeros([1, 1, self.hidden_size], device=x_example.device)
        self.nt_1 = torch.zeros([1, 1, self.hidden_size], device=x_example.device)
    
    def forward(self, x):
        assert x.ndim == 3
        
        x = self.ln(x) # layer norm on x
        
        left = self.left(x) # part left 
        right = F.silu(self.right(x)) # part right with just swish (silu) function

        left_left = left.transpose(1, 2)
        left_left = F.silu( self.drop( self.conv( left_left ).transpose(1, 2) ) )
        l_skip = self.lskip(left_left)

        # start mLSTM
        q = self.dropq(self.wq(left_left))
        k = self.dropk(self.wk(left_left))
        v = self.dropv(self.wv(left))
        
        i = torch.exp(self.lni(self.i_gate(left_left)))
        f = torch.exp(self.lnf(self.f_gate(left_left)))
        o = torch.sigmoid(self.lno(self.o_gate(left_left)))

        ct_1 = self.ct_1
        ct = f*ct_1 + i*v*k
        ct = torch.mean(self.ln_c(ct), [0, 1], keepdim=True)
        self.ct_1 = ct.detach()
        
        nt_1 = self.nt_1
        nt = f*nt_1 + i*k
        nt =torch.mean( self.ln_n(nt), [0, 1], keepdim=True)
        self.nt_1 = nt.detach()
        
        ht = o * ((ct*q) / torch.max(nt*q)) # [batchs_size, ?, hiddden_size]
        # end mLSTM
        ht = ht
        
        left = self.drop2(self.GN(ht + l_skip))
        
        out = self.ln_out(left * right)
        out = self.ln_proj(self.proj(out))
        
        return out
    
class XLstm(nn.Module):
    def __init__(self, layers, x_example, depth=4, factor=2):
        super(XLstm, self).__init__()

        self.layers = nn.ModuleList()
        for layer_type in layers:
            layer = MLstmBlock(x_example, factor, depth)
            self.layers.append(layer)
    
    def init_states(self, x):
        [l.init_states(x) for l in self.layers]
        
    def forward(self, x):
        x_original = x.clone()
        for l in self.layers:
             x = l(x) + x_original
        return x
    
class XCG(object):
    def __init__(self):
        self.name = 'XCG'
    
    # hyperparameters
    batch_size = 24 # how many independent sequences will we process in parallel?
    block_size = 124 # what is the maximum context length for predictions? # impact little
    eval_iters = 3 # more fast ( when it's low )
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    print(device)
    n_embd = 164 # impact big 

    dropout = 0.2 # no impact
    config_block = "m"
    num_heads = 8    # define number of block diagonal
    head_size = 4    # define hiddden size
    # ------------
    x = torch.zeros(batch_size, block_size, n_embd).to(device)

class Head(nn.Module):
  """one head of self-attention"""

  def __init__(self, head_size):
      super().__init__()
      self.key = nn.Linear(XCG.n_embd, head_size, bias=False)
      self.query = nn.Linear(XCG.n_embd, head_size, bias=False)
      self.value = nn.Linear(XCG.n_embd, head_size, bias=False)
      self.register_buffer('tril', torch.tril(torch.ones(XCG.block_size, XCG.block_size)))

      self.dropout = nn.Dropout(XCG.dropout)

  def forward(self, x):
    B,T,C = x.shape
    k = self.key(x)
    q = self.query(x)
    # compute attention score ("affinities")
    wei = q @ k.transpose(-2, -1) * C**-0.5
    wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
    wei = F.softmax(wei, dim=-1)# (B, T, T)
    wei = self.dropout(wei)
    # perform the weighted aggregation of the values
    v = self.value(x)
    out = wei @ v # (B, T, C)
    return out




class MultiHeadAttention(nn.Module):
  """multiple heads of self-attention in parallel"""

  def __init__(self, num_heads, head_size):
      super().__init__()
      self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
      self.proj = nn.Linear(num_heads * head_size, XCG.n_embd)
      self.dropout = nn.Dropout(XCG.dropout)

  def forward(self, x):
    out = torch.cat([h(x) for h in self.heads], dim=-1)
    out = self.dropout(self.proj(out))
    return out




class FeedForward(nn.Module):

  def __init__(self, n_embd):
    super().__init__()
    if n_embd % 2 != 0:
        print("error the embd must be divisible by 2")

    self.net = nn.Sequential(
        nn.Linear(n_embd, 4 * n_embd),
        nn.ReLU(),
        nn.Linear(4 * n_embd, n_embd),
        nn.Dropout(XCG.dropout),
    )
  def forward(self, x):
    x = self.net(x)
    return x
    



class Block(nn.Module):
  """ Transformer block: communication followed by computation"""

  def __init__(self, n_embd, n_head):
     super().__init__()
     head_size = n_embd // n_head
     self.sa = MultiHeadAttention(n_head, head_size)
     self.ffwd = FeedForward(n_embd)
     self.ln1 = nn.LayerNorm(n_embd)
     self.ln2 = nn.LayerNorm(n_embd)

  def forward(self, x):
    x = x + self.sa(self.ln1(x))
    x = x + self.ffwd(self.ln2(x))
    return x


class Transformer(nn.Module):

    def __init__(self, vocab_size, x, config_layers, device):
        super().__init__()
        self.vocab_size = vocab_size
        self.n_embd = x.shape[2]
        self.block_size = x.shape[1]
        
        self.device = device
        

        # each token directly reads off the logits for the next token from a lookup table
        self.token_embedding_table = nn.Embedding(self.vocab_size, self.n_embd)
        self.position_embedding_table = nn.Embedding(self.block_size, self.n_embd)
        
        self.xlstm = XLstm(config_layers, x)
        
        self.ln_f = nn.LayerNorm(self.n_embd)
        self.head = nn.Linear(self.n_embd, self.vocab_size)
    
    def init_states(self, x):
        self.xlstm.init_states(x)
        
    def forward(self, idx, targets=None):
        B, T = idx.shape

        # idx and targets are both (B,T) tensor of integers
        tok_emb = self.token_embedding_table(idx) # (B,T,C)
        pos_emb = self.position_embedding_table(torch.arange(T, device=self.device)) # T, C

        x = tok_emb + pos_emb # (B, T, C)

        x = self.xlstm(x)

        x = self.ln_f(x)

        logits = self.head(x)
        
        
        if targets is None:
            loss = None
        else:
            B, T, C = logits.shape
            logits = logits.view(B*T, C)
            targets = targets.view(B*T)
            loss = F.cross_entropy(logits, targets)

        return logits, loss
    
    def generate(self, idx, max_new_tokens):
        # idx is (B, T) array of indices in the current context
        for _ in range(max_new_tokens):
            # crop idx to the last self.block_size tokens
            idx_cond = idx[:, -self.block_size:]
            # get the predictions
            logits, loss = self(idx_cond)
            # focus only on the last time step
            logits = logits[:, -1, :] # becomes (B, C)
            # apply softmax to get probabilities
            probs = F.softmax(logits, dim=-1) # (B, C)
            # sample from the distribution
            idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
            # append sampled index to the running sequence
            idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
        return idx, idx_next


class XLstmApp(object):
    def __init__(self):
        self.name = 'anns.xlstm.XLstmApp'
    
    @staticmethod
    def startup(params:Dict = {}) -> None:
        print(f'XLstm应用示例 v0.0.4')
        # XLstmApp.train_main(params=params)
        XLstmApp.predict_main(params=params)

    @staticmethod
    def train_main(params:Dict = {}) -> None:
        with open('work/datas/input.txt', 'r', encoding='utf-8') as f:
            text = f.read()
        print(len(text))
        # here are all the unique characters that occur in this text
        chars = sorted(list(set(text)))
        vocab_size = len(chars)
        # create a mapping from characters to integers
        stoi = { ch:i for i,ch in enumerate(chars) }
        itos = { i:ch for i,ch in enumerate(chars) }
        encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
        XLstmApp.decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string

        # Train and test splits
        data = torch.tensor(encode(text), dtype=torch.long)
        n = int(0.1*len(data)) # first 90% will be train, rest val
        XLstmApp.train_data = data[n:]
        XLstmApp.val_data = data[:n]

        torch.set_default_device(XCG.device)
        x = torch.zeros(XCG.batch_size, XCG.block_size, XCG.n_embd)
        model = Transformer(vocab_size, x, XCG.config_block, XCG.device)
        m = model.to(XCG.device)
        paras = list(str(sum(p.numel() for p in m.parameters())))
        num = len(paras)-1
        for i in paras:
            if num % 3 == 0:
                print(i, end=" ")
                pass
            else:
                print(i, end="")
                pass
            num -= 1
        
        model = Transformer(vocab_size, x, XCG.config_block, XCG.device)
        # try:
        #     model.load_state_dict(torch.load('/kaggle/working/model'))
        #     print("model loaded")
        # except:
        #     print("not the same model")

        m = model.to(XCG.device)
        m.train()
        XLstmApp.train(m)
        print(f'^_^ The End! ^_^')

    @staticmethod
    def predict_main(params:Dict = {}) -> None:
        with open('work/datas/input.txt', 'r', encoding='utf-8') as f:
            text = f.read()
        print(len(text))
        # here are all the unique characters that occur in this text
        chars = sorted(list(set(text)))
        vocab_size = len(chars)
        # create a mapping from characters to integers
        stoi = { ch:i for i,ch in enumerate(chars) }
        itos = { i:ch for i,ch in enumerate(chars) }
        encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
        XLstmApp.decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string


        model = Transformer(vocab_size, XCG.x, XCG.config_block, XCG.device)
        model.load_state_dict(torch.load('./work/ckpts/xlstm'))
        model = model.to(XCG.device)
        context = torch.zeros((1, 1), dtype=torch.long, device=XCG.device)
        #context = torch.tensor(encode(""), dtype=torch.long, device=device)
        #context = context.view(1, context.shape[0])
        for idx in range(500):
            context, out = model.generate(context, max_new_tokens=1) # context: (batch_size, seq_len); out: (batch_size, 1)为单词索引号
            print(XLstmApp.decode(out[0].tolist()), end="")

    
    # data loading
    @staticmethod
    def get_batch(split, block_size, batch_size):
        # generate a small batch of data of inputs x and targets y
        data = XLstmApp.train_data if split == 'train' else XLstmApp.val_data
        ix = torch.randint(len(data) - block_size, (batch_size,))
        x = torch.stack([data[i:i+block_size] for i in ix])
        y = torch.stack([data[i+1:i+block_size+1] for i in ix])
        x, y = x.to(XCG.device), y.to(XCG.device)
        return x, y

    @staticmethod
    def get_batch_xlstm(split, block_size, batch_size, idx):
        # generate a small batch of data of inputs x and targets y
        data = XLstmApp.train_data if split == 'train' else XLstmApp.val_data
        if idx+block_size+batch_size > len(data):
            idx = 1
        ix = []
        [ix.append(i) for i in range(idx, idx+batch_size)]
        ix = torch.tensor(ix)
        
        x = torch.stack([data[i:i+block_size] for i in ix])
        y = torch.stack([data[i+1:i+block_size+1] for i in ix])
        x, y = x.to(XCG.device), y.to(XCG.device)
        return x, y
    
    @torch.no_grad()
    def estimate_loss(model, eval_iters, block_size, batch_size):
        out = {}
        model.eval()
        for split in ['train', 'val']:
            losses = torch.zeros(eval_iters)
            for k in range(eval_iters):
                X, Y = XLstmApp.get_batch(split, block_size, batch_size)
                logits, loss = model(X, Y)
                losses[k] = loss.item()
            out[split] = losses.mean()
        model.train()
        return out

    import random

    @torch.no_grad()
    def estimate_loss_xlstm(model, eval_iters, block_size, batch_size):
        out = {}
        for split in ['train', 'val']:
            losses = torch.zeros(eval_iters)
            idx = random.randint(0, 100000) if split == 'val' else random.randint(0, 1000000)
            for k in range(eval_iters):
                #X, Y = get_batch_xlstm(split, block_size, batch_size, idx)
                X, Y = XLstmApp.get_batch(split, block_size, batch_size)
                idx += 1     
                logits, loss = model(X, Y)
                losses[k] = loss.item()
            out[split] = losses.mean()
        model.train()
        return out
    
    @staticmethod
    def train(m):
        learning_rate = 3e-4
        optimizer = torch.optim.AdamW(m.parameters(), lr=learning_rate)
        scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 300, eta_min=1e-5)


        loss_list_t = []
        loss_list_v = []
        max_iters_total = 80000
        max_iters = int(max_iters_total/XCG.batch_size)
        eval_interval = 100

        idx = 0
        chunk_size = 25

        for iter in tqdm(range(max_iters)):

            # every once in a while evaluate the loss on train and val sets

            if iter % eval_interval == 0:
                torch.save(m.state_dict(), './work/ckpts/xlstm')

                print(optimizer.param_groups[0]["lr"])
                losses = XLstmApp.estimate_loss(m, XCG.eval_iters, XCG.block_size, XCG.batch_size)
                loss_list_t.append(losses['train'].cpu())
                loss_list_v.append(losses['val'].cpu())
                print(f"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")

            if iter % chunk_size == 0:
                m.xlstm.init_states(XCG.x)
                idx = random.randint(0, 1000000)

            # sample a batch of data
            #xb, yb = get_batch_xlstm('train', block_size, batch_size, idx)
            xb, yb = XLstmApp.get_batch('train', XCG.block_size, XCG.batch_size)
            xb = xb.to(XCG.device)
            yb = yb.to(XCG.device)
            idx += 1

            # evaluate the loss
            start = time.time()
            logits, loss = m(xb, yb)
            end = time.time()
            #print("exe time : ", (end-start)/batch_size)

            torch.nn.utils.clip_grad_norm_(m.parameters(), max_norm=0.5)

            #scheduler.step()
            optimizer.zero_grad(set_to_none=True)
            loss.backward()
            optimizer.step()


        torch.save(m.state_dict(), './work/ckpts/xlstm')
        # draw loss
        print(loss)
        plt.plot(range(len(loss_list_t)), loss_list_t)
        plt.plot(range(len(loss_list_v)), loss_list_v)
        plt.xlabel("Number of Iterations")
        plt.ylabel("Loss")
        plt.show()
    









def main(params:Dict = {}) -> None:
    XLstmApp.startup(params=params)

def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--run_mode', action='store',
        type=int, default=1, dest='run_mode',
        help='run mode'
    )
    return parser.parse_args()


if '__main__' == __name__:
    args = parse_args()
    params = vars(args)
    main(params=params)
